import Description from '@/components/Description';
import { ActionType, ProTable, type ProColumns } from '@/components/Pro';
import {
  emsControllerConfigControllerConfigPage,
  emsControllerConfigControllerUploadConfig,
} from '@/services/ess/emsControl';
import { ProForm, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import { DescriptionsItemType } from 'antd/es/descriptions';
import type { UploadFile } from 'antd/es/upload/interface';
import React, { useRef, useState } from 'react';
import { Link, useIntl, useSearchParams } from 'umi';
import Styles from './emsCtronller.less';

const EmsController: React.FC = () => {
  const intl = useIntl();
  const { stationName } = JSON.parse(sessionStorage.getItem('SiteConfigurationParams') || '{}');
  const [searchParams] = useSearchParams();
  const stationId = searchParams.get('stationId');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();

  // 当前站点信息
  const siteInfo = [
    {
      label: intl.formatMessage({ id: 'emsController.currentSite' }),
      children: stationName || 'N/A',
    },
  ];

  // 表格列定义
  const columns: ProColumns<any, 'text'>[] = [
    {
      title: intl.formatMessage({ id: 'emsController.table.number' }),
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'emsController.table.deviceCode' }),
      dataIndex: 'deviceCode',
    },
    {
      title: intl.formatMessage({ id: 'emsController.table.platformCode' }),
      dataIndex: 'devicePlatformCode',
    },
    {
      title: intl.formatMessage({ id: 'emsController.table.configPath' }),
      dataIndex: 'configStoragePath',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'emsController.table.updateTime' }),
      dataIndex: 'updatedTime',
    },
    {
      title: intl.formatMessage({ id: 'emsController.table.operations' }),
      valueType: 'option',
      render: (_, record) => [
        <Space key="operations">
          <Link
            to={`/remoteUpgrade/SiteConfigurationManagement/ems/emsCommunication?id=${record.id}&deviceCode=${record.deviceCode}&devicePlatformCode=${record.devicePlatformCode}`}
            key="communication"
          >
            <span>{intl.formatMessage({ id: 'emsController.table.communication' })}</span>
          </Link>
          <Link
            to={`/remoteUpgrade/SiteConfigurationManagement/ems/emsControllerSerial?id=${record.id}&deviceCode=${record.deviceCode}&devicePlatformCode=${record.devicePlatformCode}`}
            key="serial"
          >
            <span>{intl.formatMessage({ id: 'emsController.table.serial' })}</span>
          </Link>
        </Space>,
      ],
    },
  ];

  // 处理文件上传
  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.error(intl.formatMessage({ id: 'emsController.message.selectFile' }));
      return;
    }

    const file = fileList[0]?.originFileObj;
    if (!file) {
      message.error(intl.formatMessage({ id: 'emsController.message.invalidFile' }));
      return;
    }

    setLoading(true);
    try {
      const response = await emsControllerConfigControllerUploadConfig(
        { stationId: Number(stationId) },
        {},
        file,
      );
      if (response.success) {
        message.success(intl.formatMessage({ id: 'emsController.message.uploadSuccess' }));
        setFileList([]);
        // 刷新表格数据
        actionRef.current?.reload();
      } else {
        message.error(
          intl.formatMessage({ id: 'emsController.message.uploadFailed' }) || '上传失败',
        );
      }
    } catch (error) {
      message.error('上传失败');
      console.error('Upload error:', error);
    } finally {
      setLoading(false);
    }
  };

  // Add function to fetch table data
  const fetchTableData = async (params: {
    current: number;
    pageSize: number;
    stationId: number;
  }) => {
    try {
      const response = await emsControllerConfigControllerConfigPage({
        ...params,
        stationId: Number(stationId),
      });
      if (response.success && response.data?.records) {
        setTableData(
          response.data.records.map((item) => ({
            id: item.id,
            deviceCode: item.deviceCode,
            deviceNode: item.devicePlatformCode,
            configPath: item.configStoragePath,
            updateTime: item.updatedTime,
          })),
        );
        return {
          data: response.data.records,
          success: true,
          total: response.data.total,
        };
      }
      return { data: [], success: false };
    } catch (error) {
      console.error('Fetch table data error:', error);
      return { data: [], success: false };
    }
  };

  return (
    <div className={Styles['ems-controller']}>
      <h2 className={Styles['ems-controller-title']}>
        {intl.formatMessage({ id: 'emsController.title' })}
      </h2>
      <div className={Styles['ems-controller-site-info']}>
        <Description
          items={siteInfo as unknown as DescriptionsItemType[]}
          style={{ width: '400px' }}
        />
      </div>
      <ProForm submitter={false} style={{ marginTop: 30 }} layout="inline">
        <ProFormUploadButton
          name="file"
          label={intl.formatMessage({ id: 'emsController.upload.label' })}
          max={1}
          fieldProps={{
            name: 'file',
            listType: 'text',
            accept: '.zip,.rar',
            fileList: fileList,
            onChange: ({ fileList: newFileList }) => setFileList(newFileList as UploadFile<any>[]),
            beforeUpload: () => false,
          }}
          title={intl.formatMessage({ id: 'emsController.upload.title' })}
        />
        <Space>
          <Button type="primary" onClick={handleUpload} loading={loading}>
            {intl.formatMessage({ id: 'emsController.upload.button' })}
          </Button>
        </Space>
      </ProForm>
      <ProTable
        actionRef={actionRef}
        columns={columns as ProColumns<any, 'text'>[]}
        request={fetchTableData}
        search={false}
        pagination={{
          showQuickJumper: true,
        }}
        rowKey="id"
        dateFormatter="string"
        headerTitle=""
        style={{ marginTop: 20 }}
        loading={loading}
      />
    </div>
  );
};

export default EmsController;
